package com.ljx.blog.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.blog.article.domain.entity.FriendLink;
import com.ljx.blog.article.domain.vo.req.FriendLinkSubmitReq;
import com.ljx.blog.article.domain.vo.resp.FriendLinkResp;
import com.ljx.blog.article.mapper.FriendLinkMapper;
import com.ljx.blog.article.service.FriendLinkService;
import com.ljx.blog.common.enums.CommonStatusTypeEnum;
import com.ljx.blog.common.exception.ApiException;
import com.ljx.blog.security.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-12  22:07
 */
@Service
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkMapper, FriendLink> implements FriendLinkService {

    @Autowired
    private FriendLinkMapper friendLinkMapper;


    @Override
    public FriendLinkResp getInfo(Long friendLinkId) {
        FriendLink friendLink = friendLinkMapper.selectById(friendLinkId);
        return BeanUtil.copyProperties(friendLink, FriendLinkResp.class);
    }

    @Override
    @Transactional
    public FriendLinkResp submit(FriendLinkSubmitReq req) {
        FriendLink friendLink;
        if (Objects.isNull(req.getId())){
            checkSubmitParams(req);
            friendLink = BeanUtil.copyProperties(req, FriendLink.class);
            friendLink.setTenantId(UserUtil.tryToGetTenantId());
            friendLinkMapper.insert(friendLink);
        } else {
            friendLink = friendLinkMapper.selectById(req.getId());
            BeanUtils.copyProperties(req, friendLink);
            friendLinkMapper.updateById(friendLink);
        }
        return getInfo(req.getId());
    }

    private void checkSubmitParams(FriendLinkSubmitReq req) {
        if (StrUtil.isEmpty(req.getAvatar()) || StrUtil.isEmpty(req.getUrl()) || StrUtil.isEmpty(req.getName())){
            throw new ApiException("必要参数不能为空");
        }
    }

    @Override
    public List<FriendLinkResp> getList() {
        List<FriendLink> categories = friendLinkMapper.selectList(new LambdaQueryWrapper<FriendLink>()
                .eq(FriendLink::getStatus, CommonStatusTypeEnum.NORMAL.getKey())
                .eq(FriendLink::getTenantId, UserUtil.tryToGetTenantId()));

        return BeanUtil.copyToList(categories, FriendLinkResp.class);
    }

    @Override
    public List<FriendLink> getListByAdmin() {
        return friendLinkMapper.selectList(new LambdaQueryWrapper<FriendLink>()
                .eq(FriendLink::getTenantId, UserUtil.tryToGetTenantId()));
    }
}
